import { useEffect } from 'react';
import { useMatchRoute } from '@/hooks/useMatchRoute.js';
import { useNavigate } from 'react-router-dom';
import { useDispatch, useSelector } from 'react-redux';
import { getActiveTabPathname, getKeepAliveTabs } from '@/selector/tabs.js';
import { defaultRoute } from '@/router/index.jsx';
import { TabsAction } from '@/actions/tabs/action.js';

function getKey() {
  return new Date().getTime().toString();
}

export function useTabs() {
  // 存放页面记录
  const keepAliveTabs = useSelector(getKeepAliveTabs);
  // 当前激活的tab
  const activeTabPathname = useSelector(getActiveTabPathname);

  const matchRoute = useMatchRoute();
  const navigate = useNavigate();
  const dispatch = useDispatch();

  // 关闭tab
  const closeTab = (pathname) => {
    if (!pathname || pathname === defaultRoute.pathname) return;
    if (!keepAliveTabs) return;
    const tabs = [...keepAliveTabs];
    const index = tabs.findIndex((o) => o.pathname === pathname);
    if (!tabs[index]) {
      return;
    }
    if (tabs[index]?.pathname === activeTabPathname && tabs.length > 1) {
      if (index > 0) {
        navigate(tabs[index - 1].pathname);
      } else {
        navigate(tabs[index + 1].pathname);
      }
    }
    tabs.splice(index, 1);
    dispatch(TabsAction.setKeepAliveTabs(tabs));
  };

  // 关闭除了自己和默认标签的其它tab
  const closeOtherTab = (pathname = activeTabPathname) => {
    if (!pathname) return;
    if (!keepAliveTabs) return;

    const tabs = [...keepAliveTabs];
    const tab = tabs.find((o) => o.pathname === pathname);
    const filterTabs = tabs.filter(
      (o) => o.pathname === pathname || o.pathname === defaultRoute.pathname
    );

    dispatch(TabsAction.setKeepAliveTabs(filterTabs));

    navigate(tab?.pathname || pathname);
  };

  // 关闭除了默认标签的其它tab
  const closeAllTab = () => {
    if (!keepAliveTabs) return;

    const tabs = [...keepAliveTabs];
    const tab = tabs.find((o) => o.pathname === defaultRoute.pathname);
    const filterTabs = tabs.filter((o) => o.pathname === defaultRoute.pathname);

    dispatch(TabsAction.setKeepAliveTabs(filterTabs));

    if (tab) {
      navigate(tab.pathname);
    }
  };

  // 刷新tab
  const refreshTab = (pathname = activeTabPathname) => {
    if (!pathname) return;
    if (!keepAliveTabs) return;

    const tabs = [...keepAliveTabs];
    const index = tabs.findIndex((tab) => tab.pathname === pathname);

    if (index >= 0) {
      // 这个是react的特性，key变了，组件会卸载重新渲染
      tabs[index].key = getKey();
    }

    dispatch(TabsAction.setKeepAliveTabs(tabs));
  };

  // 设置标签标题
  const setTabTitle = (title) => {
    if (!activeTabPathname) return;
    if (!keepAliveTabs) return;

    const tabs = [...keepAliveTabs];
    const index = tabs.findIndex((tab) => tab.pathname === activeTabPathname);

    if (tabs[index].title !== title) {
      tabs[index].title = title;
      dispatch(TabsAction.setKeepAliveTabs(tabs));
    }
  };

  useEffect(() => {
    if (!matchRoute) return;
    if (!keepAliveTabs) return;

    const tabs = [...keepAliveTabs];
    const index = tabs.findIndex((o) => o.pathname === matchRoute?.pathname);
    const existKeepAliveTab = tabs[index];

    // 如果不存在则需要插入
    if (!existKeepAliveTab) {
      tabs.push({
        title: matchRoute?.title,
        key: getKey(),
        pathname: matchRoute?.pathname,
        children: matchRoute?.children
      });

      dispatch(TabsAction.setKeepAliveTabs(tabs));
    } else if (existKeepAliveTab.pathname !== matchRoute?.pathname) {
      // 如果是同一个路由，但是参数不同，我们只需要刷新当前页签并且把pathname设置为新的pathname， children设置为新的children
      if (index >= 0) {
        tabs[index].key = getKey();
        tabs[index].pathname = matchRoute?.pathname;
        tabs[index].children = matchRoute?.children;
      }

      dispatch(TabsAction.setKeepAliveTabs(tabs));
    }

    dispatch(TabsAction.setActiveTabPathname(matchRoute?.pathname));
  }, [matchRoute]);

  return {
    tabs: keepAliveTabs,
    activeTabPathname,
    closeTab,
    closeOtherTab,
    closeAllTab,
    refreshTab,
    setTabTitle
  };
}
